import 'package:faker/models/local_rss.dart';
import 'package:sqflite/sqlite_api.dart';

import 'base_provider.dart';

class LocalRssProvider extends BaseDbProvider {
  final String tbName = "local_rss";

  final String columnId = "id";
  final String columnIcon = "icon";
  final String columnTag = "tag";
  final String columnTitle = "title";
  final String columnSummary = "summary";
  final String columnAuth = "auth";
  final String columnRoute = "route";
  final String columnParameter = "parameter";
  final String columnExample = "example";
  final String columnPriorityValue = "priorityValue";
  final String columnUpdateDate = "updateDate";

  LocalRssProvider();

  @override
  tableName() {
    return tbName;
  }

  @override
  createTableString() {
    return '''
        CREATE TABLE $tbName($columnId INTEGER PRIMARY KEY AUTOINCREMENT, $columnTag INTEGER, $columnIcon TEXT, $columnTitle TEXT,
        $columnSummary TEXT, $columnAuth TEXT, $columnRoute TEXT, $columnParameter TEXT, $columnExample TEXT, $columnPriorityValue INTEGER, $columnUpdateDate TEXT)
      ''';
  }

  ///查询所有数据库
  Future<List> getAllLocalRssProvider() async {
    Database db = await getDataBase();
    var result = await db.rawQuery("select * from $tbName");
    return result.toList();
  }

  ///查询数据库
  Future<LocalRss> getLocalRssByRoute(String route) async {
    Database db = await getDataBase();
    var result = await db
        .rawQuery("select * from $tbName WHERE $columnRoute = '$route'");
    if (result.length == 0) return null;
    return LocalRss.fromMap(result.first);
  }

  ///插入到数据库
  Future<int> insert(LocalRss item) async {
    Database db = await getDataBase();
    var userProvider = await getLocalRssByRoute(item.route);
    if (userProvider != null) {
      ///删除数据
      await db
          .delete(tbName, where: "$columnRoute = ?", whereArgs: [item.route]);
    }
    var res = await db.insert("$tbName", item.toMap());
    print(res.toString());
    return res;
  }

  Future<void> delete(id) async {
    Database db = await getDataBase();
    await db.delete(tbName, where: "$columnId = ?", whereArgs: [id]);
  }

  ///更新数据库
  Future<int> update(LocalRss item) async {
    Database db = await getDataBase();
    return await db.update("$tbName", item.toMap(),
        where: "$columnId = ?", whereArgs: [item.id]);
  }

  /// 关闭数据库
  Future<void> close() async {
    Database db = await getDataBase();
    await db.close();
  }
}
